<template>
  <el-row type="flex" class="row-bg" justify="center">
    <el-col :xl="6" :lg="7">
      <h2>欢迎来到VueAdmin管理系统</h2>
      <el-image :src="require('@/assets/manster.jpg')" style="height: 180px;width: 180px;"></el-image>
      <p>QQ:1249041911</p>
      <el-link type="info" href="https://gitee.com/manster1231" target="_blank">Gitee:https://gitee.com/manster1231</el-link>
    </el-col>
    <el-col :span="1">
      <el-divider direction="vertical"></el-divider>
    </el-col>
    <el-col :xl="6" :lg="7">
      <el-tabs stretch type="border-card" v-model="activeName">
        <el-tab-pane label="登录" name="login">
          <el-form :model="loginForm" :rules="loginRules" ref="loginForm" label-width="100px" class="demo-loginForm">
            <el-form-item label="用户名" prop="username" style="width: 380px;">
              <el-input placeholder="请输入用户名" v-model="loginForm.username"></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password" style="width: 380px;">
              <el-input placeholder="请输入密码" v-model="loginForm.password" show-password></el-input>
            </el-form-item>
            <el-form-item label="验证码" prop="code" style="width: 380px;">
              <el-input placeholder="请输入验证码" v-model="loginForm.code" style="width: 150px; float: left;" maxlength="5"></el-input>
              <el-image :src="captchaImg" class="captchaImg" @click="getCaptcha"></el-image>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="submitLoginForm('loginForm')">登录</el-button>
              <el-button @click="resetForm('loginForm')">重置</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="注册" name="register">
          <el-form :model="registerForm" :rules="registerRules" ref="registerForm" label-width="100px" class="demo-loginForm">
            <el-form-item label="用户名" prop="username" style="width: 380px;">
              <el-input placeholder="请输入用户名" v-model="registerForm.username"></el-input>
            </el-form-item>
            <el-form-item label="城市" prop="username" style="width: 380px;">
              <el-input placeholder="请输入城市,例如:杭州" v-model="registerForm.city"></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password" style="width: 380px;">
              <el-input placeholder="请输入密码" v-model="registerForm.password" show-password></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email" style="width: 380px;">
              <el-input placeholder="请输入邮箱" v-model="registerForm.email"></el-input>
            </el-form-item>
            <el-form-item label="验证码" prop="code" style="width: 380px;">
              <el-input placeholder="请输入验证码" v-model="registerForm.code" style="width: 150px; float: left;" maxlength="5"></el-input>
              <el-button v-show="sendAuthCode" type="primary" @click="getEmailCode">发送验证码</el-button>
              <el-button v-show="!sendAuthCode" type="primary">{{ authTime }} s</el-button>

            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="submitRegisterForm('registerForm')">注册</el-button>
              <el-button @click="resetForm('registerForm')">重置</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
      </el-tabs>
    </el-col>
  </el-row>
</template>

<script>
import qs from 'qs'
import axios from "axios";
export default {
  name: "Login",
  data() {
    return {
      activeName: 'login', //激活的tab-pane
      sendAuthCode: true, // true为按钮,false为倒计时
      authTime: 120,  // 倒计时
      loginForm: {
        username: 'admin',
        password: '123456',
        code: '',
        token: '',
      },
      registerForm: {
        username: '',
        password: '',
        email: '',
        code: '',
        city: ''
      },
      captchaImg: null,
      loginRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' }
        ],
        code: [
          { required: true, message: '请输入验证码', trigger: 'blur' },
          { min: 5, max: 5, message: '长度为 5 个字符', trigger: 'blur' }
        ],
      },
      registerRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        city: [
          { required: true, message: '请输入城市', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
        ],
        code: [
          { required: true, message: '请输入验证码', trigger: 'blur' },
          { min: 5, max: 5, message: '长度为 5 个字符', trigger: 'blur' }
        ]
      }
    };
  },
  created() {
    this.getCaptcha()
  },
  watch:{
    $route(to,from){
      this.getCaptcha()
    }
  },
  methods: {
    // 倒计时
    getAuthCode(){
      //如果已经在倒计时了就删掉原来的倒计时
      if(this.authTimeTimer){
        clearTimeout(this.authTimeTimer)
      }
      this.authTimeTimer = setTimeout(() => {
        this.authTime -= 1;
        //倒计时完成,重新显示按钮
        if(this.authTime < 0){
          this.sendAuthCode = true;
          clearTimeout(this.authTimeTimer);
        }else {
          //没完成就继续计时
          this.getAuthCode()
        }
      }, 1000)
    },
    // 进行注册
    submitRegisterForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          axios.post('/register',this.registerForm).then(res => {
            //注册成功，发送消息
            this.$message({
              message: res.data.data,
              type: "success"
            })
            //跳转pane
            this.activeName='login'
          })
        } else {
          return false;
        }
      });
    },
    //注册获取email验证码
    getEmailCode(){
      //验证email是否正确
      this.$refs['registerForm'].validateField('email', (valid) => {
        if (!valid){
        this.$message({
          message: "邮件正在发送中，请稍后",
          type: "success"
        })
          //进行计时
          this.authTime = 120;
          this.sendAuthCode = false;
          this.getAuthCode();

          axios.get('/sendEmail/' + this.registerForm.email).then(res => {
            this.$message({
              message: res.data.data,
              type: "warn"
            });
          })
        }else{
          return false;
        }
      })

    },
    //提交表单
    submitLoginForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          axios.post('/login?' + qs.stringify(this.loginForm)).then(res => {
            if(res.data.code === 400){
              if(res.data.msg === "Bad credentials"){
                res.data.msg = "用户名或密码错误"
              }
              this.$message({
                message: res.data.msg,
                type: 'error'
              });
              this.getCaptcha()
            }else {
              //登录验证成功，从header中获取jwt
              const jwt = res.headers['authorization']
              //提交状态信息
              this.$store.commit('SET_TOKEN', jwt)
              //跳转页面
              this.$router.push("/index")
            }
          })
        } else {
          return false;
        }
      });
    },
    //重置表单内容
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    //获取验证码图片
    getCaptcha() {
      this.$axios.get('/captcha').then(res => {
        this.loginForm.token = res.data.token
        this.captchaImg = res.data.captchaImg
        this.loginForm.code = ''
      })
    }
  }
}
</script>

<style scoped>

.el-row {
  background-color: #fafafa;
  height: 100%;
  display: flex;
  align-items: center;
  text-align: center;
  justify-content: center;
}

.el-divider {
  height: 250px;
}
.captchaImg {
  float: left;
  margin-left: 8px;
  border-radius: 4px;
  width: 120px;
  height: 40px;
}
.el-form {
  width: 420px;
  margin: 50px auto;
}
</style>